﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace TestDrivenDevelopment.Models
{
    public interface ITaskRepository
    {
        string[] GetTasks();
    }

    public class TaskRepository : ITaskRepository
    {
        public static string ConnectionString
        {
            get
            {
                return ConfigurationManager.ConnectionStrings[Environment.MachineName].ConnectionString;
            }
        }


        public string[] GetTasks()
        {
            var table = new DataTable();
            using (IDbConnection connection = new SqlConnection(ConnectionString))
            {
                connection.Open();
                using (IDbCommand cmd = connection.CreateCommand())
                {
                    cmd.CommandText = "SELECT Description FROM Tasks";
                    cmd.CommandType = CommandType.Text;
                    using (IDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                    {
                        table.Load(reader);
                    }
                }
            }

            string[] retval = new string[table.Rows.Count];
            for (int i = 0; i < table.Rows.Count; i++)
            {
                retval[i] = (string) table.Rows[i][0];
            }
            return retval;
        }
    }
}